package com.study.zzedu.ui.home;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.aliyun.player.alivcplayerexpand.util.database.DatabaseHelper;
import com.aliyun.player.alivcplayerexpand.util.database.DatabaseManager;
import com.aliyun.player.alivcplayerexpand.util.database.LongVideoDatabaseManager;
import com.aliyun.player.alivcplayerexpand.util.download.AliyunDownloadManager;
import com.aliyun.solution.longvideo.utils.SettingSpUtils;
import com.aliyun.svideo.common.utils.PermissionUtils;
import com.study.zzedu.R;
import com.study.zzedu.fragment.center.StudyCenterFragment;
import com.study.zzedu.fragment.home.VideoTabFragment;
import com.study.zzedu.fragment.notice.NoticeFragment;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.OkHttpUtils;
import com.study.zzedu.widget.BottomBar;
import com.study.zzedu.widget.ChoiceCourseDialog;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by kiros on 2020/9/3.
 */

public class HomeActivity extends AppCompatActivity {

    private TextView tv_notice_count;
    private BottomBar bottomBar;
    public static final int PERMISSION_REQUEST_CODE = 1000;
    private SettingSpUtils spUtils;
    private AliyunDownloadManager mAliyunDownloadManager;
    //LongVideoBean longVideoBean;
    /**
     * 权限申请
     */
    String[] permission = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spUtils = new SettingSpUtils.Builder(this).create();
        initView();
        getNotReadNoticeCount();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getstate();

            }
        },3000);

        NoticeFragment.setOnNoticeCountChange(new NoticeFragment.OnCountChange() {
            @Override
            public void onChange(boolean unRead) {
                //true : 无未读  false：有未读
                if(!unRead){
                    tv_notice_count.setVisibility(View.VISIBLE);
                }else {
                    tv_notice_count.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    protected void initView() {
        tv_notice_count = findViewById(R.id.tv_notice_count);
        bottomBar = findViewById(R.id.bottom_bar);
        bottomBar.setContainer(R.id.fl_container)
                .setTitleBeforeAndAfterColor("#666666", "#3399ff")
                .addItem(VideoTabFragment.class,
                        getString(R.string.my_course),
                        R.mipmap.group1,
                        R.mipmap.group)
                .addItem(NoticeFragment.class,
                        getString(R.string.notice),
                        R.mipmap.notice,
                        R.mipmap.notice2)
                .addItem(StudyCenterFragment.class,
                        getString(R.string.study_center),
                        R.mipmap.msg,
                        R.mipmap.msg2)
                .build();
    }

    private void getstate(){
        OkHttpUtils.getInstance(HomeActivity.this).getJsonForString(OkHttpUtils.BASE_URL + "/appCourseSubject/checkCourseSelectionTime",
                null, null, new OkHttpUtils.HttpCallBack() {

            @Override
            public void onSuccess(String obj) {
                try {
                    JSONObject jObject = new JSONObject(obj);
                    if (0 == jObject.getInt("code")) {
                        JSONArray jsonArray = jObject.getJSONArray("data");
                        if (jsonArray.length() > 0) {
                            final String d = jsonArray.getJSONObject(0).getString("curTerm");
                            if(TextUtils.isEmpty(d)){
                                LogUtil.e("forget","不需要选课");
                            }else {
                                ChoiceCourseDialog cd = new ChoiceCourseDialog.Builder(HomeActivity.this,d).create();
                                cd.show();
                            }
                        }
                    } else {
                    }
                } catch (Exception e) {
                    e.toString();
                }
            }

            @Override
            public void onSuccess(JSONObject obj) {
            }

            @Override
            public void onError(String msg) {
            }
        });
    }
    private void getNotReadNoticeCount(){
        OkHttpUtils.getInstance(HomeActivity.this).getJsonForString(OkHttpUtils.BASE_URL + "/appNotice/getNotReadNoticeCount",
                null, null, new OkHttpUtils.HttpCallBack() {

                    @Override
                    public void onSuccess(String obj) {
                        try {
                            JSONObject jObject = new JSONObject(obj);
                            if (0 == jObject.getInt("code")) {
                                JSONArray jsonArray = jObject.getJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    String count = jsonArray.get(0).toString();
                                    if("0".equals(count))
                                        tv_notice_count.setVisibility(View.INVISIBLE);
                                    else
                                        tv_notice_count.setVisibility(View.VISIBLE);

                                }
                            } else {
                            }
                        } catch (Exception e) {
                            e.toString();
                        }
                    }

                    @Override
                    public void onSuccess(JSONObject obj) {
                    }

                    @Override
                    public void onError(String msg) {
                    }
                });
    }
    @Override
    protected void onStart() {
        super.onStart();
        boolean checkResult = PermissionUtils.checkPermissionsGroup(this, permission);
        if (!checkResult) {
            PermissionUtils.requestPermissions(this, permission, PERMISSION_REQUEST_CODE);
        }else{
            init();
        }
    }

    private void init(){
        initDataBase();
    }

    private void initDataBase(){
        DatabaseManager.getInstance().createDataBase(this, DatabaseHelper.DB_PATH);
        LongVideoDatabaseManager.getInstance().createDataBase(this);
        mAliyunDownloadManager = AliyunDownloadManager.getInstance(getApplicationContext());

        startDownLoad();
    }

    /**
     *设置下载个数
     */
    private void startDownLoad() {
        //同时下载数量
        String number = spUtils.getVideoNumber();
        int num = 1;
        if (!TextUtils.isEmpty(number)) {
            num = Integer.valueOf(spUtils.getVideoNumber());
        }
        mAliyunDownloadManager.setMaxNum(num);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (!isAllGranted) {
                showPermissionDialog();
            }else{
                // 如果所有的权限都授予了
                init();
            }
        }
    }
    private AlertDialog mPermissionAlertDialog;
    //系统授权设置的弹框
    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mPermissionAlertDialog = builder.setMessage(getString(com.aliyun.solution.longvideo.R.string.app_name) + getString(com.aliyun.solution.longvideo.R.string.alivc_longvideo_request_permission_content_text))
                .setPositiveButton(com.aliyun.solution.longvideo.R.string.alivc_longvideo_request_permission_positive_btn_text, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        startActivity(intent);
                        mPermissionAlertDialog.dismiss();

                    }
                })
                .setNegativeButton(com.aliyun.solution.longvideo.R.string.alivc_longvideo_request_permission_negative_btn_text, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setCancelable(false)
                .create();
        mPermissionAlertDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
